import { GameConfigData } from "./GameConfig";

const { ccclass, property } = cc._decorator;
export let audioMgrs: AudioMgr;
@ccclass
export default class AudioMgr {

    _audioData = {};
    gameMusicId = 0;

    static init() {
        audioMgrs = new AudioMgr();
        window["audioMrgs"] = audioMgrs;
        audioMgrs.preloadMusic();
    }

    preloadMusic() {
        this.onLodeAudioRes("music", this.saveGameAudio.bind(this), "start");
    }

    playGameAudio(name) {
        if (name != "music") {
            if (GameConfigData.isSound != 1) return
        }
        else {
            if (GameConfigData.isMusic != 1) return
        }

        if (this._audioData[name]) {
            //不是背景音乐
            if (name.indexOf("music") != -1) {
                if (cc.audioEngine.isLoop(this.gameMusicId)) return;
                if (this.gameMusicId) return;
                this.gameMusicId = cc.audioEngine.play(this._audioData[name], true, 0.5);
                cc.audioEngine.setLoop(this.gameMusicId, true);
            }
            else {
                cc.audioEngine.play(this._audioData[name], false, 1);
            }
        }
        else {
            this.onLodeAudioRes(name, this.saveGameAudio.bind(this));
        }
    }

    stopGameAudio() {
        cc.audioEngine.stop(this.gameMusicId);
        this.gameMusicId = null;
    }

    saveGameAudio(audio, audioName, type = "play") {
        this._audioData[audioName] = audio;
        if (type != "start") this.playGameAudio(audioName);
    }

    onLodeAudioRes(audioName, callback, type = "") {
        cc.loader.loadRes("music/" + audioName, function (err, audio) {
            if (err == null) callback(audio, audioName, type)
        });
    }

}
